package com.example.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blog.domain.LoveList;
import com.example.blog.domain.UuId;
import com.example.blog.mapper.LoveListMapper;
import com.example.blog.service.LoveListService;
import com.example.blog.utils.UploadTheFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Service
public class LoveListServiceImpl extends ServiceImpl<LoveListMapper, LoveList> implements LoveListService {
    private final UuIdServiceImpl uuIdService;
    @Autowired
    public LoveListServiceImpl( UuIdServiceImpl uuIdService){
        this.uuIdService = uuIdService;
    }
    @Override
    public String uploadImg(MultipartFile[] file) {
        UploadTheFile uploadTheFile =new UploadTheFile();
        //如果文件个数不是一个，并且文件类型不对，返回空
        if(UploadTheFile.fileFormat(file) || file.length!=1)
            return null;
        List<String> keys = uuIdService.randomUUid(file.length);
        //上传图片后，返回地址
        List<String> path =  uploadTheFile.uploadFile(file,keys);
        //插入生成的uuid数据存储
        List<UuId> uuIds = new ArrayList<>();
        for (String s : path) {
            UuId uuId = new UuId();
            uuId.setUuidValue(s);
            uuIds.add(uuId);
        }
        uuIdService.saveBatch(uuIds);
        return path.get(0);
    }



    @Override
    public Integer delImg(String oldImg) {
        UploadTheFile uploadTheFile =new UploadTheFile();
        //检查传来的文件名是否有‘/’有，则进行截取‘/’后的字符，再进行删除
        String[] fileName = UploadTheFile.intercept(new String[]{oldImg}, "/");
        // 删除oss存储的图片返回删除成功数量
        int length = uploadTheFile.deleteFile(fileName);
        //删除数据库的uuid
        LambdaQueryWrapper<UuId> wrapper = new LambdaQueryWrapper<>();
        uuIdService.remove(wrapper.eq(UuId::getUuidValue, oldImg));
        return length;
    }
}
